package sample;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.io.*;

public class LoginController {


    private String xueHao;
    private String Psw;

    @FXML
    private Button loginBtn;

    @FXML
    private TextField psw;
    @FXML
    private Label hint;

    @FXML
    private TextField xuehao;


    @FXML
    void Login(ActionEvent event) {  //先把得到的学号密码写入文件，再运行py脚本，得到登录结果进行页面的切换

        xueHao=xuehao.getText()+'\n';
        Psw=psw.getText();
        String result = null; //登录的结果


        //将得到的账号密码写入文件
        java.io.File file =new java.io.File("src/res/info.txt");
        java.io.PrintWriter output= null;
        try {
            output = new java.io.PrintWriter(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        output.print(xueHao);
        output.print(Psw);
        output.close();


        //执行登录的py脚本，得到登录结果
        Process proc;
        try {
            //String[] args = new String[]{"python3","src/res/login.py"};
            proc = Runtime.getRuntime().exec("python3 src/res/login.py");// 执行py文件
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null)
            {

                result=line.substring(line.length()-1);
            }

            in.close();
            try {
                proc.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        if(result.equals("y")) //登录成功跳转到到课表界面
        {

            //删除学生的密码
            java.io.File file2 =new java.io.File("src/res/info.txt");
            java.io.PrintWriter output2= null;
            try {
                 output2=new java.io.PrintWriter(file2);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            output2.print(xueHao);

            output2.close();

            //删除学生教务处的response
            File file3 =new File("src/res/result.txt");
            try {
                FileWriter fileWriter =new FileWriter(file3);
                fileWriter.write("");
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            SceneManager.SwitchToSchedulePage(event);


        }
        else
        {
            hint.setText("登录失败！");
        }


    }

}
